package model;

import model.command.Command;
import utils.Const;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class WALLogger {

    private final String logFilePath = Const.dataDir + File.separator + "wal.log";

    //记录日志条目
    public synchronized void log(Command command) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(logFilePath, true);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(command);
            oos.flush();
        } catch (IOException e) {
            throw new IOException("写入WAL日志失败", e);
        }
    }

    //读取所有日志条目，用于重放
    public synchronized List<Command> readAll() throws IOException {
        List<Command> entries = new ArrayList<>();
        File file = new File(logFilePath);
        if (!file.exists()) {
            return entries;
        }
        try (FileInputStream fis = new FileInputStream(logFilePath);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            while (true) {
                try {
                    Object obj = ois.readObject();
                    if (obj instanceof Command) {
                        entries.add((Command) obj);
                    }
                } catch (EOFException e) {
                    //读取完毕
                    break;
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new IOException("读取WAL日志失败", e);
        }
        return entries;
    }

    //清除日志 在恢复完毕后调用
    public synchronized void clear() {
        File file = new File(logFilePath);
        if (file.exists()) {
            file.delete();
        }
    }
}
